import { useEffect, useState, useRef } from 'react';
import './App6.css';
import { Input, Space, Table, Popconfirm } from 'antd';
const { Search } = Input;


function App() {
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '操作',
            dataIndex: 'do',
            key: 'do',
            render: (a, item) => (

                dataSource.length >= 1 ? (
                    <Space size="middle">
                        <Popconfirm title="确认删除？" onConfirm={() => { onDelete(item.id) }}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </Space>
                ) : null
            )
        }
    ];

    let [dataSource, setData] = useState([]);



    function getData() {
        fetch('http://localhost:3001/data', {
            method: 'get'
        }).then((res) => {
            if (!res.ok) console.log('请求失败');
            // console.log(data);
            // return JSON.stringify(data);
            return res.json();
        })
            .then(data => {
                // console.log(data);
                setData(data);
            })
    }

    useEffect(() => {
        getData()
    }, [])


    let input = useRef(null);
    function onSearch(name) {
        // console.log(val);

        fetch(`http://localhost:3001/data?name=${name}`, {
            method: 'get'
        }).then((res) => {
            return res.json();
        }).then((data) => {
            console.log(data);

            setData(data)
        })
    }


    function onDelete(id) {
        fetch(`http://localhost:3001/data/${id}`, {
            method: 'delete',
        }).then((res) => {
            return res.json()
        }).then((data) => {
            console.log(data);

            // for (let i = 0; i < data.length; i++) {
            //     if (data[i].id == id) {
            //         data.splice(i, 1);
            //     }
            // }
        })
    }


    return (
        <div className="container">
            <div className="search-box">
                <Search
                    placeholder='请输入用户姓名'
                    enterButton="搜索"
                    size="large"
                    allowClear
                    ref={input}
                    onSearch={onSearch}
                />
            </div>

            <Table
                dataSource={dataSource}
                columns={columns}
                pagination={false}
            />
        </div>
    )
}

export default App;